package com.zhaojk.audio.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhaojk.audio.service.PicServiceImpl;
import com.zhaojk.audio.util.TimeTrace;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhaojk
 */
@RestController
@RequestMapping("/api/pic")
@Slf4j
public class PicController {
    @Autowired
    private PicServiceImpl picService;

    /**
     * 根据prompt生成图片，每次返回结果不同
     * @param prompt
     * @return
     */
    @PostMapping("/getOne")
    public ResponseEntity<List> getOne(@RequestParam String prompt) {
        JSONObject pictureObject = picService.queryPic(prompt);
        String url = "";
        if(pictureObject != null){
            JSONArray image_urls = pictureObject.getJSONObject("data").getJSONArray("image_urls");
            if(image_urls.size() > 0){
                url = image_urls.getString(0);
            }
        }
        Map result = new HashMap<>();
        List resultList = new ArrayList<>();
        result.put("url", url);
        result.put("alt", prompt);
        resultList.add(result);

        return new ResponseEntity(resultList, HttpStatus.OK);
    }

    /**
     * 上传图片到火山引擎的 tos
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<String> upload(String url, String objectKey) {
        try {
            picService.upload2Tos(url, objectKey);
        } catch(Exception e){
            log.info("上传文件到tos失败");
            return new ResponseEntity("上传文件失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }

        return new ResponseEntity("成功", HttpStatus.OK);
    }

    /**
     * 获取图片url
     *
     * @return
     */
    @PostMapping("/getUrl")
    @TimeTrace("获取图片")
    public ResponseEntity<List> getUrl(@RequestParam(value = "prompt") String prompt) {
        String url;
        try {
            url = picService.getUrl(prompt);
            Map result = new HashMap<>();
            List resultList = new ArrayList<>();
            result.put("url", url);
            result.put("alt", prompt);
            resultList.add(result);
            return new ResponseEntity(resultList, HttpStatus.OK);
        } catch(RuntimeException e){
            return new ResponseEntity("获取图片URL失败", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
